package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiWXMain*
 * @Description:对接微信公众号主接口
 * @author: LJT* @date 2019-12-17 02:28:00
 *
 */

public class apiWXToken implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXToken.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String DBS = "dataSource";

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        JSONObject result = new JSONObject();
        JSONObject datatoken = new JSONObject();

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取嵌入传递的参数
        String opsource = request.getParameter("opsource");

        // 非空校验检查检查
        if (KHUtil.isNull(opsource)) {
            result.put("code", -1);
            result.put("msg", KHUtil.isNullMSG("opsource", opsource));
            return result.toString();

        } else {

            try {
                // 检查当前Token状态
                String APPID = "";
                String APPSECRET = "";

                if (opsource == "wxc") {
                    APPID = KHDBConfig.getParam(eliteBean, "WX1-ID");
                    APPSECRET = KHDBConfig.getParam(eliteBean, "WX1-KE");

                } else if (opsource == "wxs") {
                    APPID = KHDBConfig.getParam(eliteBean, "WX2-ID");
                    APPSECRET = KHDBConfig.getParam(eliteBean, "WX2-KE");


                } else if (opsource == "minip") {
                    APPID = KHDBConfig.getParam(eliteBean, "WX3-ID");
                    APPSECRET = KHDBConfig.getParam(eliteBean, "WX3-KE");

                } else {

                    log.warn("未知类型公众号嵌入警告:" + opsource);

                    result.put("code", -1);
                    result.put("msg", "未知类型公众号嵌入警告:" + opsource);
                    return result.toString();
                }
                log.debug("获取到的微信公众号配置信息【APPID】：" + APPID + "【APPSECRET】：" + APPSECRET);

                // 查询当前微信公众号Token信息
                List selectExits = eliteBean.chaxun_sql("select TOKEN, EXPIRED from wx_accesstoken where DEL_FLAG = 0 AND DATE_ADD(CREATEDTIME,INTERVAL EXPIRED second) > NOW() and WX_ID = '" + APPID + "' limit 1", DBS);
                if (selectExits.size() > 0) {
                    Map selectExitsm = selectExits.get(0);
                    String TOKEN = selectExitsm.get("TOKEN");
                    int EXPIRED = selectExitsm.get("EXPIRED");

                    result.put("code", 1);
                    result.put("msg", "查询完成");
                    datatoken.put("access_token", TOKEN);
                    datatoken.put("expires_in", EXPIRED);
                    result.put("data", datatoken);

                } else {
                    // 调用微信获取最新Token
                    String wxTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;
                    String wxTokenResult = Util.doHttpGet(wxTokenURL, "UTF-8", 5000, 0);
                    JSONObject wxTokenJson = JSONObject.parseObject(wxTokenResult);

                    String access_token = wxTokenJson.getString("access_token");
                    int expires_in = wxTokenJson.getInteger("expires_in");

                    if (KHUtil.isNull(access_token)) {

                        int errcode = wxTokenJson.getInteger("errcode");
                        String errmsg = wxTokenJson.getString("errmsg");

                        result.put("code", errcode);
                        result.put("msg", errmsg);
                        result.put("data", datatoken);

                    } else {
                        // eliteBean.update("update wx_accesstoken set del_flag = 1 where del_flag = 0 and WX_ID = '" + APPID + "'", DBS);
                        eliteBean.update("delete from wx_accesstoken where WX_ID = '" + APPID + "'", DBS);
                        eliteBean.update("INSERT INTO wx_accesstoken (REC_ID, TOKEN, CREATEDTIME, EXPIRED, DEL_FLAG, WX_ID) VALUES (UUID(), '" + access_token + "', NOW(), " + expires_in + ", 0, '" + APPID + "')", DBS);

                        result.put("code", 1);
                        result.put("msg", "更新完成");
                        datatoken.put("access_token", access_token);
                        datatoken.put("expires_in", expires_in);
                        result.put("data", datatoken);
                    }


                }

            } catch (Exception e1) {
                log.error("接口处理异常", e1);
                // 失败返回

                result.put("code", -1);
                result.put("msg", e.getMessage());
                result.put("data", datatoken);

            }
        }

        log.debug("获取Token处理完成返回结果:" + result.toString());

        return result.toString();
    }

}
